<link rel="stylesheet" href="__STATIC__/mobile/default/css/myaddress.css?v=2">
<link rel="stylesheet" href="__STATIC__/mobile/default/css/cityPicker.css">
<link rel="stylesheet" href="__STATIC__/mobile/default/css/userData.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vant@2.12/lib/index.css"/>
<link rel="stylesheet" href="__STATIC__/css/hs.css" />
<style type="text/css">
	.header{background-color:{$setcolor} !important; }
    .van-nav-bar {
        line-height: 46px;
    }
</style>
<div class="page-hd" id="app">

<van-popup v-model="show" round position="bottom">
  <van-cascader
    v-model="cascaderValue"
    title="请选择所在地区"
    :options="options"
    @close="show = false"
    @finish="onFinish"
    @change="onChange"
  />
</van-popup>
</div>


<script src="https://cdn.jsdelivr.net/npm/vant@2.12/lib/vant.min.js"></script>
<script type="text/html" id="addressListTpl">
<div class="{$isAddOrder==1?'wrapper':''} addressesList ">
    {eq name="$isAddOrder" value="1"}
	<div class="page">
    <div class="page-hd">
        <div class="header bor-1px-b">
            <div class="header-left">
                <a href="javascript:;" class="left-arrow close_wrapper" data-type="list"></a>
            </div>
            <div class="header-title">选择地址</div>
            <div class="header-right"></div>
        </div>
    </div>
    {/eq}
    <div class="page-bd">
		<ul class="addresslist goodslist">
	
		</ul>
   </div>
    <div class="page-ft">
        <a href="javascript:;" class="fs32 fw_b color_w BGcolor_r add_address">新增收货地址</a>
    </div>
</div>
</div>

<div class="wrapper addressInfoBox">

</div>
</script>
<script src="__STATIC__/js/jquery/jquery-weui.min.js"></script>


<!--地址列表-->
<script type="text/html" id="addressLiTpl">
    {{each list as item index}}
    <li>
        <object>
            <div class="block" data-index="{{index}}">
                <div class="address">
                    <div class="info">
                        <div><p class="fs30 fw_b color_3">{{item.consignee}} {{item.mobile}}</p></div>
                        <span class="fs28 color_9">{{item.merger_name}}{{item.address}}</span></div>
                    <img src="__STATIC__/mobile/default/images/rightIcon.png" alt="">
                </div>
				
				
                <div class="radioBox">
                    <label for="address_{{item.address_id}}">
                        <div class="iconBox">
                            <input type="radio" class="check editDefault" name="radiobox" id="address_{{item.address_id}}"
                                   value="{{item.address_id}}" {{item.is_default==1?'checked':''}}>
                            <i class="icon_checked"></i>
                        </div>
                        <span class="fs26 color_9">设为默认地址</span>
                    </label>
                    <a href="javascript:;" class="edit fs26 color_9" data-index="{{index}}"><img src="__STATIC__/mobile/default/images/edit.png" alt=""></a>
                </div>
            </div>
            <div class="swiped BGcolor_3">
                <div class="delect" data-address_id="{{item.address_id}}"><img src="__STATIC__/mobile/default/images/delectIcon.png" alt=""></div>
            </div>
        </object>
    </li>
    {{/each}}
</script>
<!--编缉或添加地址-->
{literal}
<script type="text/html" id="addressInfoTpl">

    <div class="page-hd">
        <div class="header bor-1px-b">
            <div class="header-left">
                <a href="javascript:;" class="left-arrow close_wrapper" data-type="list"></a>
            </div>
            <div class="header-title">{{if address_id }}修改地址{{else}}添加地址{{/if}}</div>
            <div class="header-right"></div>
        </div>
    </div>
	<form action="" id="formAddress">
    <div class="page-bd userData">
        <!-- 页面内容-->
        <div class="cells">
          <div class="cell">
            <div class="cell_bd"><span class="fs28 color_9">收货人</span></div>
            
            <div class="cell_ft">
                 <input type="text" class="fs28  color_3" placeholder="请输入收货人姓名" name="consignee" value="{{consignee}}">
            </div>
          </div>
          <div class="cell">
              <div class="cell_bd">
            <span class="fs28 color_9">手机号码</span></div>
            <div class="cell_ft">
              <input type="text" class="fs28  color_3" placeholder="请输入收货人电话" name="mobile" value="{{mobile}}">
            </div>
          </div>
          <div class="cell bankType cell_access">
              <div class="cell_bd chooseArea"><span class="fs28 color_9">所在地区</span></div>
              <div class="cell_ft chooseArea">
                <div id="areaName" class="fs28 fw_b color_3 bankBox"></div>
              </div>
          </div>
          <div class="cell">
            <div class="cell_bd">
            <span class="fs28 color_9">详细地址</span></div>
            <div class="cell_ft">
             <input type="text" class="fs28  color_3" placeholder="请输入详细地址" name="address" value="{{address}}">
            </div>
          </div>
        </div> 
		<input type="hidden" name="address_id" value="{{address_id}}">
		
        <div class="page-ft">
            <a class="fs32 color_w fw_b BGcolor_r postAddress" onclick="evalPost();">{{if address_id }}确认修改{{else}}确认添加{{/if}}</a>
          </div>
      </div>
    </div>
	</from>
 </script>
{/literal}
<script type="text/javascript">
    var isAddOrder = '{$isAddOrder|intval}';
    console.log(isAddOrder==1)
    var addressList = {};
    var defAddressId = 0;
	$(function(){
		if(isAddOrder==1){
			$("body").append(template('addressListTpl'));
		}else{
			$(".page-hd").append(template('addressListTpl'));
		}
//		 $({$isAddOrder==1?'"body"':'".page-hd"'}).append(template('addressListTpl'));
	})
	
    var app = new Vue({
      el: '#app',
      data: {
          show: false,
          fieldValue: '',
          cascaderValue: '',
          // 选项列表，children 代表子选项，支持多级嵌套
          options: [],
          finallyArr: [],
          sumbitArr: []
      },
      mounted(){
        this.getAreaInfo(1)
        console.log('初始化')  
      },
        methods: {
            getAreaInfo(level, parent_code, indexArr) {
                jq_ajax('{:url("member/api.address/getRegion")}',{parent_id: parent_code, selected: level},(res)=>{
                    if (level == 1) {
                        this.options = res.data.map(item => {
                            const base = {text: item.name, value: item.code}
                            return Object.assign(base, {children: []})
                        })
                    }else if(level == 2){
                        this.options[indexArr[0]].children = res.data.map(item => {
                            const base = {text: item.name, value: item.code}
                            return Object.assign(base, {children: []})
                        })
                    }else if(level == 3){
                        if (res.data.length > 0) {
                            this.options[indexArr[0]].children[indexArr[1]].children = res.data.map(item => {
                                const base = {text: item.name, value: item.code}
                                return Object.assign(base, {children: []})
                            })
                        }else{
                            this.onFinish({selectedOptions:this.finallyArr})
                        }
                    }else if(level == 4){
                        if (res.data.length > 0) {
                            this.options[indexArr[0]].children[indexArr[1]].children[indexArr[2]].children = res.data.map(item => {
                                return {text: item.name, value: item.code}
                            })
                        }else{
                            this.onFinish({selectedOptions:this.finallyArr})
                        }

                    }
                }, 'GET') 
            },
            onChange({ value, selectedOptions, tabIndex }) {
                this.finallyArr = selectedOptions
                let indexArr = []
                if (tabIndex == 0) {
                    const index = this.options.findIndex( item => item.value == value )
                    indexArr.push(index)
                }else if(tabIndex == 1) {
                    const parentIndex = this.options.findIndex( item => item.value == selectedOptions[0].value )
                    const index = this.options[parentIndex].children.findIndex( item => item.value == value )
                    indexArr.push(parentIndex, index)
                }else if(tabIndex == 2) {
                    const parentIndex = this.options.findIndex( item => item.value == selectedOptions[0].value )
                    const childindex = this.options[parentIndex].children.findIndex( item => item.value == selectedOptions[1].value )
                    const index = this.options[parentIndex].children[childindex].children.findIndex( item => item.value == value )
                    indexArr.push(parentIndex, childindex, index)
                }
                this.getAreaInfo(tabIndex + 2, value, indexArr)
            },
            onFinish({ selectedOptions }) {
              this.sumbitArr = selectedOptions
              this.show = false;
              this.fieldValue = selectedOptions.map((option) => option.text).join(' ');
              const dom = document.getElementById('areaName')
              dom.innerHTML = this.fieldValue
              console.log('do',)
            },
        },
    })
	
    //获取收货地址区列表
    function getAddressList() {
        jq_ajax('{:url("member/api.address/getList")}', '', function (res) {
            if (res.code == 0) {
                _alert(res.msg);
                return false;
            }
            addressList = res.list;
            if (isAddOrder == 1) {

                if (typeof(res.list) == 'undefined') {
                    $('.addressBox .tips').show();
                    $('.addressBox .address').hide();
                    return false;
                }
                showAddress(addressList[0]);
                evalShippingFee();//计算运费
                defAddressId = addressList[0]['address_id'];
            }
            

            $('.addresslist').html(template('addressLiTpl', res));
            container('.addresslist object')
        })
    }

    //设置显示指定收货地址
    function showAddress(address) {
        $('.address').find('._consignee').html(address.consignee + ' ' + address.mobile);
        $('.address').find('._address').html(address.merger_name + ' ' + address.address);
        $('#address_id').val(address.address_id);
    }

    $(function () {
        getAddressList();
    })
    //点击删除地址
    $(document).on('click','.addresslist .delect',function() {
        jq_ajax('{:url("member/api.address/delete")}','address_id='+$(this).data('address_id'),function(res){
            if (res.code == 0) {
                alert(res.msg);
                return false;
            }
            addressList = res.list;
            $('.addresslist').html(template('addressLiTpl', res));
            container('.addresslist object');
        })
    })
    //关闭编缉弹出
    $(document).on('click','.addressInfoBox .close_wrapper',function () {
        $('html').removeClass('noscroll');
        $('.addressInfoBox').removeClass('move-left');
    })

    //点击新增地址
    $(document).on('click','.add_address', function () {
        $('html').addClass('noscroll');
        $('.addressInfoBox').html(template('addressInfoTpl'));
        $('.addressInfoBox').addClass('move-left');
        app.cascaderValue = ''
        app.fieldValue = ''
        app.finallyArr = []
        app.sumbitArr = []
        // app.show = true
        // console.log('点击',app.show)
        // $("#city-picker").cityPicker({
        //     title: "请选择省市区"
        // });
    })
    //点击编缉收货地址
    $(document).on('click', '.addresslist .edit', function () {
        const info = addressList[$(this).data('index')]
        isContainer = true;
        $('.addressInfoBox').html(template('addressInfoTpl', addressList[$(this).data('index')]));
        $('html').addClass('noscroll');
        $('.addressInfoBox').addClass('move-left');
        $('#areaName').html(info.merger_name.split(',').join(' '))
        app.cascaderValue = ''
        app.fieldValue = ''
        app.finallyArr = [info.province, info.city, info.district]
        app.sumbitArr = [info.province, info.city, info.district]
        console.log('info',info)
        // const dom = document.getElementById('areaName')
        // dom.innerHTML = this.fieldValue
        // $("#city-picker").cityPicker({
        //     title: "请选择省市区"
        // });
    })
    
    // 点击弹出vue的地址选择
    
    $(document).on('click', '.chooseArea', function () {
        app.show = true
    })
    
    
    //提交修改或添加操作
    var isClick = true;
    function evalPost(){
        var postData = $('#formAddress').toJson();
        postData.regionIds = $(document).find('#city-picker').data('codes');
        if (app.sumbitArr.length > 0) {
            if ( typeof(app.sumbitArr[0]) == 'object') {
                const arr = app.sumbitArr.map(item => item.value)
                postData.regionIds = arr.join(',')
            }else{
                postData.regionIds = app.sumbitArr.join(',')
            }
        }
        var url = postData.address_id > 0 ?  '{:url("member/api.address/edit")}':'{:url("member/api.address/add")}';
        if(isClick){
        	isClick= false;
	        jq_ajax(url,postData,function(res){
	            if (res.code == 0) {
	                _alert(res.msg);
	                return false;
	            }
	            $('.addressBox .tips').hide();
	            $('.addressBox .address').show();
	            addressList = res.list;
	            $('.addresslist').html(template('addressLiTpl', res));
	            container('.addresslist object');
	            $('.addressInfoBox .close_wrapper').trigger("click");
	        })
	        setTimeout(function(){
	        	isClick=true;
	        },1000)
	    }
        
    }
    //设置为默认地址
    $(document).on('click','.addresslist .editDefault',function() {
        var obj = $(this);
        if (defAddressId != obj.val()) {
            jq_ajax('{:url("member/api.address/editDefault")}', 'address_id=' + $(this).val(),function (res){
                if (res.code == 0) {
                    _alert(res.msg);
                    return false;
                }
                defAddressId = obj.val();
            })
        }

    })
</script>
